package com.fjec.activity.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fjec.activity.entity.BizGiveGiftDetail;
import com.fjec.activity.entity.BizUserGift;
import com.fjec.activity.entity.BizUserGiftChangeRecord;
import com.fjec.activity.feign.BaseClient;
import com.fjec.activity.feign.MarketClient;
import com.fjec.activity.mapper.BizUserGiftMapper;
import com.fjec.activity.service.IBizUserGiftChangeRecordService;
import com.fjec.activity.service.IBizUserGiftService;
import com.fjec.activity.service.IRPCService;
import com.fjec.activity.view.UserGiftVO;
import com.fjec.common.enums.EnumSysCode;
import com.fjec.common.exception.BizException;
import com.fjec.common.protocol.JsonResult;
import com.fjec.common.setting.Setting;
import com.fjec.common.shiro.AccountInfo;
import com.fjec.common.util.DateUtil;
import com.fjec.common.util.SequenceIdGenerator;
import org.apache.commons.collections.MapUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.*;

/**
 * <p>
 * 001.用户礼物表 服务实现类
 * </p>
 *
 * @author admin
 * @since 2020-09-18
 */
@Service
public class BizUserGiftServiceImpl extends ServiceImpl<BizUserGiftMapper, BizUserGift> implements IBizUserGiftService {

    @Resource
    private BizUserGiftMapper mapper;

    @Resource
    private IBizUserGiftChangeRecordService bizUserGiftChangeRecordService;

    @Resource
    private IRPCService rpcService;

    @Autowired
    private MarketClient marketClient;

    @Autowired
    private SequenceIdGenerator idGenerator;

    @Autowired
    private BaseClient baseClient;

    @Transactional(rollbackFor = Throwable.class)
    @Override
    public JsonResult getUserGiftsByUserId(Long userId) {
        List<Map<String, Object>> giftInfos = rpcService.getGiftInfo(3);

        List<BizUserGift> userGifts = this.list(new QueryWrapper<BizUserGift>().eq("UserId", userId));
        List<UserGiftVO> userGiftVOS = new ArrayList<>();

        for (Map<String, Object> giftInfo : giftInfos) {
            Long giftId = MapUtils.getLong(giftInfo, "Id");
            Optional<BizUserGift> bizUserGiftOptional = userGifts.stream().filter(userGift -> userGift.getGiftId().equals(giftId)).findFirst();

            if (bizUserGiftOptional.isPresent()) {
                BizUserGift userGift = bizUserGiftOptional.get();
                UserGiftVO userGiftVO = UserGiftVO.builder()
                        .id(userGift.getId())
                        .userId(userGift.getUserId())
                        .giftId(userGift.getGiftId())
                        .giftName(MapUtils.getString(giftInfo, "ServName"))
                        .giftNum(userGift.getGiftNum())
                        .amount(MapUtils.getInteger(giftInfo, "Amount"))
                        .valid(MapUtils.getInteger(giftInfo, "Valid"))
                        .servPic(MapUtils.getString(giftInfo, "ServPic"))
                        .delFlag(MapUtils.getInteger(giftInfo, "DelFlag"))
                        .build();
                userGiftVOS.add(userGiftVO);
            } else {
                // 如果用户礼物表中不存在当前用户某种礼物记录，则初始化数量0的记录
                BizUserGift bizUserGift = new BizUserGift();
                bizUserGift.setUserId(AccountInfo.getUserId());
                bizUserGift.setGiftId(giftId);
                bizUserGift.setGiftNum(0);
                bizUserGift.setCreateTime(DateUtil.nowLdt());
                bizUserGift.setUpdateVer(0);
                this.save(bizUserGift);
                // end

                UserGiftVO userGiftVO = UserGiftVO.builder()
                        .id(bizUserGift.getId())
                        .userId(bizUserGift.getUserId())
                        .giftId(giftId)
                        .giftName(MapUtils.getString(giftInfo, "ServName"))
                        .giftNum(0)
                        .amount(MapUtils.getInteger(giftInfo, "Amount"))
                        .valid(MapUtils.getInteger(giftInfo, "Valid"))
                        .servPic(MapUtils.getString(giftInfo, "ServPic"))
                        .delFlag(MapUtils.getInteger(giftInfo, "DelFlag"))
                        .build();
                userGiftVOS.add(userGiftVO);
            }
        }
        return JsonResult.success().data(userGiftVOS).build();
    }

    @Override
    public Long buyGifts(List<UserGiftVO> gifts) {
        Integer totalCharge = 0;
        List<Map<String, Object>> productList = new ArrayList<>();
        for (UserGiftVO userGiftVO : gifts) {
            if (userGiftVO.getRequireNum() == null)
                continue;
            int numToBuy = userGiftVO.getRequireNum() - userGiftVO.getGiftNum();
            if (numToBuy > 0) {
                // 需要礼物购买
                totalCharge += numToBuy * userGiftVO.getAmount();
                Map<String, Object> product = new HashMap<>();
                product.put("servId", userGiftVO.getGiftId());
                product.put("num", numToBuy);
                product.put("marketCode", 0);
                productList.add(product);
            }
        }

        // 限制最大支付额
        Map<String, Object> settingMap = baseClient.getSysSetting();
        Setting setting = new Setting(settingMap);
        if (totalCharge > Integer.parseInt(setting.getMaxOrderAmount())) {
            return -1L;
        }

        if (totalCharge > 0) {
            //调用服务订单生成接口
            int orderType = 3;
            String subOpenId = AccountInfo.getOpenId();
            Long userId = AccountInfo.getUserId();
            Long orderId = marketClient.saveServOrder(totalCharge, orderType, productList, subOpenId, userId);
            if (orderId == null || orderId == -1)
                return null;
            return orderId;
        }
        return null;
    }

    @Transactional(rollbackFor = Throwable.class)
    @Override
    public int buyGiftsSuccessfully(List<UserGiftVO> gifts, Long orderId) {
        // 首先rpc调用market服务，设置servorder状态为已支付
        int code = marketClient.setServOrderStatus2(orderId);
        if (code == -1)
            return -1;
        if (code == 2)
            return 0;
        Long userId = AccountInfo.getUserId();

        // 用户礼物变动表
        List<BizUserGiftChangeRecord> records = new ArrayList<>();

        for (UserGiftVO g : gifts) {
            if (g.getRequireNum() == null)
                continue;
            // 若购买数量小于等于0，则跳过
            g.setNumToBuy(g.getRequireNum() - g.getGiftNum());
            if (g.getNumToBuy() <= 0)
                continue;

            BizUserGift userGift = this.getOne(
                    new QueryWrapper<BizUserGift>().eq("UserId", userId).eq("GiftId", g.getGiftId()));

            if (userGift != null) {
                userGift.setGiftNum(g.getRequireNum());
                userGift.setUpdateTime(DateUtil.nowLdt());
                this.updateById(userGift);
            } else {
                userGift = new BizUserGift();
                userGift.setId(idGenerator.nextId());
                userGift.setUserId(userId);
                userGift.setGiftId(g.getGiftId());
                userGift.setGiftNum(g.getRequireNum());
                userGift.setCreateTime(DateUtil.nowLdt());
                userGift.setUpdateVer(0);
                this.save(userGift);
            }

            // 礼物变动记录
            BizUserGiftChangeRecord changeRecord = new BizUserGiftChangeRecord();
            changeRecord.setUserGiftId(userGift.getId());
            changeRecord.setNum(g.getNumToBuy());
            changeRecord.setOpeType(1);
            changeRecord.setBusiData(String.valueOf(orderId));
            changeRecord.setCreateTime(DateUtil.nowLdt());
            records.add(changeRecord);
        }
        bizUserGiftChangeRecordService.saveBatch(records);
        return 0;
    }

    @Override
    public int putUserGifts(List<Map<String, Object>> boughtGifts, Long orderId) {
        List<BizUserGiftChangeRecord> records = new ArrayList<>();

        for (Map<String, Object> gift : boughtGifts) {
            Long userId = MapUtils.getLong(gift, "userId");
            Long giftId = MapUtils.getLong(gift, "giftId");
            Integer num = MapUtils.getInteger(gift, "num");
            BizUserGift userGift = this.getOne(
                    new QueryWrapper<BizUserGift>().eq("UserId", userId).eq("GiftId", giftId));

            if (userGift != null) {
                userGift.setGiftNum(userGift.getGiftNum() + num);
                userGift.setUpdateTime(DateUtil.nowLdt());
                this.updateById(userGift);
            } else {
                userGift = new BizUserGift();
                userGift.setId(idGenerator.nextId());
                userGift.setUserId(userId);
                userGift.setGiftId(giftId);
                userGift.setGiftNum(num);
                userGift.setCreateTime(DateUtil.nowLdt());
                userGift.setUpdateVer(0);
                this.save(userGift);
            }

            // 礼物变动记录
            BizUserGiftChangeRecord changeRecord = new BizUserGiftChangeRecord();
            changeRecord.setUserGiftId(userGift.getId());
            changeRecord.setNum(num);
            changeRecord.setOpeType(1);
            changeRecord.setBusiData(String.valueOf(orderId));
            changeRecord.setCreateTime(DateUtil.nowLdt());
            records.add(changeRecord);
        }

        bizUserGiftChangeRecordService.saveBatch(records);
        return 0;

    }
}
